<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>2</title>
</head>
<body>
    <script>

        // 封装一个函数，实现将对象类型的数据转化为字符串
        function format(obj){
            let str = '';
            for (const key in obj) {
                str += `&${key}=${obj[key]}`
            }
            str = str.slice(1);
            return str;
        }

        // ajxs请求封装 将其放进对象中
        let http = {
            // 方式一：get方式
            get:function(url,data,call){
                let xhr = new XMLHttpRequest();
                xhr.open('get',url+'?'+format(data));
                xhr.send();
                xhr.onreadystatechange = function(){
                    if(xhr.readyState == 4 && xhr.status == 200){
                        let res = JSON.parse(xhr.responseText);
                        console.log(res);
                        call(res);
                    }
                }
            },


            // 方式二：post方式
            post:function(url,data,call){
                let xhr = new XMLHttpRequest();
                xhr.open('post',url);
                // 模仿form表单
                // xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
                // xhr.send(format(data));

                // 发送json数据
                xhr.setRequestHeader('Content-type','application/json');
                xhr.send(JSON.stringify(data));
                xhr.onreadystatechange = function(){
                    if(xhr.readyState == 4 && xhr.status == 200){
                        let res = JSON.parse(xhr.responseText);
                        call(res);
                    }
                }
            },


            // 方式三：
            ajxs:function(obj){
                if(obj.type == 'get'){
                    this.get(obj.url,obj.data,obj.sucess);
                }else if(obj.type == 'post'){
                    this.post(obj.url,obj.data,obj.sucess);
                }
            }

        }


        // 调用

        let obj = {name:'小张'}

        // get方式请求
        http.get('//139.9.177.51:3333/api/testGet',obj,function(res){
            console.log(res);
        })

        // post方式请求
        http.post('//139.9.177.51:3333/api/testPost',obj,function(res){
            console.log(res);
        })

        // 万能方式请求
        // get方式
        let obj1 = {
            type:'get',
            url:'//139.9.177.51:3333/api/testGet',
            data:obj,
            sucess:function(res){
                console.log(res);
            }
        }
        http.ajxs(obj1);

        // post方式
        let obj2 = {
            type:'post',
            url:'//139.9.177.51:3333/api/testPost',
            data:obj,
            sucess:function(res){
                console.log(res);
            }
        }
        http.ajxs(obj2);

        
    </script>
</body>
</html>